<template>
  <div class="loginView">
    
    <div class="login">
      <h1 style="color: rgba(28, 104, 219, 0.904)">LOGIN</h1>
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="user"
        :rules="rules"
        ref="user"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-row :gutter="18">
            <!-- 添加gutter来设置行内元素间距 -->
            <el-col :span="12">
              <!-- 18/24 = 75% 宽度，以适应输入框和按钮 -->
              <el-input
                v-model="user.captcha"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col :style="{ width: '100px' }">
              <!-- 6/24 = 25% 宽度，用于按钮 -->
              <el-button
                type="primary"
                :disabled="isButtonDisabled"
                @click="getCaptcha"
              >
                {{ countdownText }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-row>
        <el-button type="primary" @click="logon('user')">登录</el-button>
        <el-button type="warning" @click="toRegister">去注册</el-button>
      </el-row>
    </div>
    <div class="title">
      <!-- 在css中设置了图片 -->
    </div>
  </div>
</template>
<script>
import { login } from "../api/usrMG";
import { sendEmail } from "../api/emailSend";
export default {
  name: "LoginView",
  data() {
    return {
      labelPosition: "right",
      user: {
        email: "", //邮箱
        password: "", //密码
        captcha: "", //验证码
      },
      isButtonDisabled: false,
      countdownSeconds: 6,
      countdownText: "获取验证码",
      rules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: this.validateEmail, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          // { min: 8, max: 16, message: '长度在8 到 16 个字符', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 6,
            max: 6,
            message: "验证码应由大小写字母和数字组成的6位字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    validateEmail(rule, value, callback) {
      //检测邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (value === "") {
        callback(new Error("请输入邮箱地址"));
      } else if (!emailRegex.test(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    },

    getCaptcha() {
      //发送验证码，点击验证码倒计时
      if (!this.user.email) {
        //未输入邮箱
        this.$message.error("请先输入邮箱");
        return;
      }

      this.validateEmail(null, this.user.email, (error) => {
        if (error) {
          // 邮箱格式验证失败
          this.$message.error("请输入正确的邮箱地址");
        } else {
          // 邮箱格式验证成功
          // 在这里可以调用你的后端 API 来获取验证码
          // 例如: sendEmail(this.user.email);
          sendEmail(this.user.email)
            .then((res) => {
              if (res.data.code == 200) this.$message.success(res.data.msg);
              else this.$message.error(res.data.msg);
            })
            .catch((err) => {
              console.log(err);
            });

          this.isButtonDisabled = true;
          this.countdownSeconds = 6; // 重置倒计时秒数
          this.countdownText = this.countdownSeconds + "s";

          const intervalId = setInterval(() => {
            if (this.countdownSeconds > 0) {
              this.countdownSeconds--;
              this.countdownText = this.countdownSeconds + "s";
            } else {
              clearInterval(intervalId);
              this.isButtonDisabled = false;
              this.countdownText = "获取验证码"; // 重置按钮文本
            }
          }, 1000);
        }
      });
    },
    logon(formName) {
      //登录事件
      console.log("登录");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.user)
            .then((res) => {
              //先判断登录是否成功
              if (res.data.code == 200) {
                // console.log(res.data.data.userId);
                this.$message.success(res.data.msg);
                //成功把返回的userId保存在前端,1秒钟之后在跳出然后跳转
                localStorage.setItem("userId", res.data.data.userId);
                localStorage.setItem("head",res.data.data.head)
                //跳转页面
                this.$router.push("/product");
              } else {
                this.$message({
                  type: "error",
                  showClose: true,
                  message: res.data.code + ":" + res.data.msg,
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    toRegister() {
      //返回登录
      this.$router.push("/register");
    },
  },
  created() {
    if (localStorage.getItem("userId") != null) {
      this.$router.push("/product");
    }
  },
};
</script>
<style>
.loginView {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 95vh;
  /* 使 .loginView 占据整个视口高度 */
}

.login {
  width: 500px;
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  /* 其他样式，如背景色、边框等 */
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2); /* 更强烈的凸出效果 */
}

.title {
  background-image: url(../assets/login.jpg);
  width: 400px;
  height: 500px;
  display: flex;
  background-size: cover; /* 这将使背景图像覆盖整个容器，同时保持宽高比 */
  background-position: center; /* 这将确保图像从中心开始放置 */
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2); /* 更强烈的凸出效果 */
}
body {
  margin: 0;
}
</style>
